package com.demo.service.impl;
 
import com.demo.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
 
@Service
public class FileServiceImpl implements FileService {
 
    private static final String UTF_8 = "UTF-8";
 
 
    /**
     *  通过@value注解
     *  把配置文件application.yaml中的值（define.nginx.path）拿过来
     *  给downloadPath赋值
     */
    @Value("${define.nginx.downloadPath}")
    private String downloadPath;
 
    /**
     * 文件上传：用户 将自己电脑上的的文件 上传到 服务器filePath路径下
     * @param file ：文件
     * @param filePath:文件上传地址
     * @param fileName：文件名称
     */
 
    @Override
    public void saveFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }
 
    /**
     * 文件下载：用户 把服务器上的文件 下载 到自己的电脑上
     * @param filename：文件名称
     * @param model
     */
    @Override
    public void download(HttpServletResponse response, String filename, Model model) {
 
        response.setContentType("application/force-download");
        response.setCharacterEncoding(UTF_8);
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(filename));
        byte[] buff = new byte[1024];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;
 
        try {
            outputStream = response.getOutputStream();
 
            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File(downloadPath + filename )));
            int read = bis.read(buff);
 
            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
            System.out.println("--------------------------------");
            model.addAttribute("result","下载失败");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}